package org.muxiao.seckill.exception;

import lombok.extern.slf4j.Slf4j;
import org.muxiao.seckill.vo.RespBean;
import org.muxiao.seckill.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespBean exceptionHandler(Exception e) {

        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespBeanEnum());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
            respBean.setMessage("参数校验异常~: " + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());

            Map<String, String> map = new HashMap<>();
            ex.getBindingResult().getFieldErrors().forEach(fieldError -> {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            respBean.setObj(map);

            return respBean;
        }

        return RespBean.error(RespBeanEnum.ERROR);
    }


    /**
     * @ExceptionHandler({MethodArgumentNotValidException.class})
     * 如果 controller包抛出了数据校验异常, 就由handleValidException()处理
     * 数据校验异常就是 MethodArgumentNotValidException.class
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public RespBean handleValidException(MethodArgumentNotValidException e) {

        //输出日志,观察异常的信息
        // log.error("数据校验出现问题-->{}, 异常类型是-->{}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>();

        //得到BindingResult
        BindingResult bindingResult = e.getBindingResult();

        //遍历bindingResult 将校验错误信息收集map
        bindingResult.getFieldErrors().stream().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return RespBean.error(RespBeanEnum.BIND_ERROR, map);
    }

    /**
     * 编写方法, 处理没有精确匹配到的异常/错误
     * 返回一个统一的信息,方便前端处理
     */
    @ExceptionHandler(value = {Throwable.class})
    public RespBean handleException(Throwable e) {
        return RespBean.error(RespBeanEnum.UNKNOWN_EXCEPTION);
    }
}
